﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using KC.DataAccess.MV6;
using KC.DataAccess.BuggerAll;

namespace KC.Business.Meta.Jobs
{
	public class BlogCleanupJob : JobBase
	{
		protected override void PreProcess_Global()
		{
			dcMV6 = new DataAccess.MV6.MV6DataContext();
		}
		protected override void Process_Global()
		{
			UpdateResults("Retagged "+RetagAllPosts().ToString()+" Posts", false);
			BuildRssFeeds();
			CleanupOldDebugInfos();
			CleanupOldErrors();
			UpdateResults("Deleted " + CleanupOldErrors().ToString() + " errors", false);
		}
		protected override void PostProcess_Global()
		{
		}

		#region Implementation

		/// <summary>Retags all Posts.</summary>
		private static int RetagAllPosts()
		{
			return KC.Business.Blog.Utils.UpdateAllTags();
		}
		/// <summary>Builds the RSS feeds for the site.</summary>
		private static void BuildRssFeeds()
		{
			// TODO: BuildRssFeeds()
		}
		/// <summary>Cleans up old errors from the MV6 database and returns count affected</summary>
		/// <returns>Count affected</returns>
		private int CleanupOldErrors()
		{
			using (MV6DataContext dc = new MV6DataContext())
			{
				var oldErrors = from e in dc.Errors
								where e.datetime < DateTime.Now.AddMonths(-3)
								select e;
				dc.Errors.DeleteAllOnSubmit(oldErrors);
				int num = oldErrors.Count();
				dc.SubmitChanges();
				return num;
			}
		}
		/// <summary>Cleans up old DebugInfos from the BuggerAll database and returns count affected</summary>
		/// <returns>Count affected</returns>
		private static int CleanupOldDebugInfos()
		{
			using (BuggerAllDataContext dc = new BuggerAllDataContext())
			{
				var di = from d in dc.DebugInfos
						 where d.DateTime < DateTime.Now.AddMonths(-3)
						 select d;
				int count = di.Count();
				dc.DebugInfos.DeleteAllOnSubmit(di);
				dc.SubmitChanges();
				return count;
			}
		}

		#endregion Implementation
	}
}
